package br.com.fiap.mercadinho.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import br.com.fiap.mercadinho.bean.User;
import br.com.fiap.mercadinho.common.DAOException;
import br.com.fiap.mercadinho.common.GenericDAOException;
import br.com.fiap.mercadinho.common.UserType;

public class UserDAO extends GenericDAO{

	private static final String EXIST_USER_QUERY = " SELECT USER_ID,         " +
													"       LOGIN,           " +
													"       TYPE,            " +
													"       PASSWORD         " +
													" FROM USER              " +
													" WHERE LOGIN = ?        " +
													"  AND PASSWORD = MD5(?) ";
	
	private static final String INSERT_USER = " INSERT INTO USER (USER_ID,LOGIN,TYPE,PASSWORD) VALUES (0,?,?,MD5(?)) ";
	
	private static final String EXIST_LOGIN_QUERY = " SELECT USER_ID,         " +
			"       LOGIN,           " +
			"       TYPE,            " +
			"       PASSWORD         " +
			" FROM USER              " +
			" WHERE LOGIN = ?        ";
			

	
	public UserDAO() {
		// TODO Auto-generated constructor stub
	}
	
	public User findUserByLoginAndPass (String login, String password) throws DAOException{
		
		try {
			openConnection();
			PreparedStatement pst = conn.prepareStatement(EXIST_USER_QUERY);
			pst.setString(1, login);
			pst.setString(2, password);
			ResultSet rs = pst.executeQuery();
			
			if (rs.next()){
				return buildUser(rs);
			}else{
				return null;
			}
			
		} catch (GenericDAOException | SQLException e) {
			throw new DAOException("UserDAO.existUser() error: " + e.getMessage());
		}
		
	}
	
	public User findUserByLogin (String login) throws DAOException{
		
		try {
			openConnection();
			PreparedStatement pst = conn.prepareStatement(EXIST_LOGIN_QUERY);
			pst.setString(1, login);
			ResultSet rs = pst.executeQuery();
			
			if (rs.next()){
				return buildUser(rs);
			}else{
				return null;
			}
			
		} catch (GenericDAOException | SQLException e) {
			throw new DAOException("UserDAO.existUser() error: " + e.getMessage());
		}
		
	}
	
	
	public void addUser(User user) throws DAOException{
		
		try {
			openConnection();
			PreparedStatement pst = conn.prepareStatement(INSERT_USER);
			pst.setString(1, user.getLogin());
			pst.setString(2, user.getUserType().getValue());
			pst.setString(3, user.getPassword());
			
			pst.executeUpdate();
			
		} catch (GenericDAOException | SQLException e) {
			throw new DAOException("UserDAO.existUser() error: " + e.getMessage());
		}
	}

	private User buildUser(ResultSet rs) throws SQLException {
		User user = new User();
		user.setId(rs.getInt("USER_ID"));
		user.setLogin(rs.getString("LOGIN"));
		user.setPassword(rs.getString("PASSWORD"));
		user.setUserType(UserType.fromString(rs.getString("TYPE")));
		
		return user;
	}
	

}
